# myapp/management/commands/filewatch.py

import time

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.core.management.base import BaseCommand
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer


# 新文件处理器类，继承自FileSystemEventHandler
class NewFileHandler(FileSystemEventHandler):
    # 当检测到新文件创建时调用
    def on_created(self, event):
        # 只处理文件，不处理目录
        if not event.is_directory:
            print(f"新文件检测到: {event.src_path}")
            self.process_file(event.src_path)

    # 处理新文件的逻辑
    # 修改 process_file()
    def process_file(self, file_path):
        print(f"正在解析文件: {file_path}")
        try:
            with open(file_path, 'r') as f:
                # content = f.read()
                # print("📦 文件内容：")
                # print(content)

                print("文件解析完成")
                # ✅ 广播 WebSocket 消息
                channel_layer = get_channel_layer()
                async_to_sync(channel_layer.group_send)(
                    "file_watch_group",
                    {
                        "type": "send_new_file",  # 注意下方消费者的调用名称是 send_new_file
                        "filename": file_path
                    }
                )
                print("文件发送成功")

        except Exception as e:
            print(f"读取文件出错: {e}")


# 自定义命令类，继承自BaseCommand
class Command(BaseCommand):
    # 命令帮助信息
    help = '监听指定文件夹中新文件，并处理它们'

    # 命令执行逻辑
    def handle(self, *args, **kwargs):
        # 指定监听的文件夹路径
        folder_to_watch = 'D:\codePython\djangoProject\\temp'  # TODO: 替换为你想监听的文件夹路径
        print(f"开始监听文件夹: {folder_to_watch}")

        # 创建新文件处理器实例
        event_handler = NewFileHandler()
        # 创建观察者实例
        observer = Observer()
        # 为观察者设置监听路径和事件处理器
        observer.schedule(event_handler, folder_to_watch, recursive=False)
        # 启动观察者
        observer.start()

        # 保持程序运行，直到收到中断信号
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            # 处理中断信号，停止观察者
            print("监听终止")
            observer.stop()
        # 等待观察者线程结束
        observer.join()
